package com.example.esp8266.activity.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.esp8266.R;
import com.example.esp8266.activity.MainActivity;
import com.example.esp8266.activity.utile.ECGeoCoordinateTransformUtil;
import com.example.esp8266.activity.utile.LocationUtils;
import com.example.esp8266.activity.utile.MouthpieceTool;
import com.example.esp8266.activity.utile.SocketLink;
import com.example.esp8266.activity.wifi.WifiUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExpertFragment extends Fragment implements View.OnClickListener{
    View view;
    private SocketLink socketLink;
    MainActivity mainActivity;
    private MouthpieceTool mouthpieceTool;
    Button btSendLocation; //发送定位
    Button btSIMState;    // SIM卡状态
    Button lockInTimeBt; //同步时间
    Spinner scanLightLevelSp; //扫码枪亮度等级
    Button lightLevelSubmitBt;
    private int lightLevel;
    private String lightSubmitStr;
    LinearLayout setAlarmTime;
    private final List<String> options1Items = new ArrayList<>();
    private final List<List<String>> hoursItems = new ArrayList<>();
    private final List<List<List<String>>> minItems = new ArrayList<>();
    private StringBuilder stringBuilder;
    private  String stringBuilderStr;
    Button alarmSubmitBt;
    Button alarmCloseBt;
    TextView alarmTimeTv;
    TextView chooseTv;
    private AlertDialog dialog;
    TextView simStateTv;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_expert, container, false);
        init();
        mainActivity = (MainActivity) getActivity();
        if (mainActivity != null){
            socketLink = mainActivity.getSocketLink();
            mouthpieceTool = mainActivity.getMouthpieceTool();
        }
        if (!EventBus.getDefault().isRegistered(this)) { //判断是否注册，避免重复注册
            EventBus.getDefault().register(this);
        }
         return view;
    }

    public void init(){
        simStateTv= view.findViewById(R.id.simState_tv);
        chooseTv = view.findViewById(R.id.choose_tv);
        alarmTimeTv = view.findViewById(R.id.alarmTime_tv);
        alarmSubmitBt = view.findViewById(R.id.alarmSubmit_bt);
        alarmSubmitBt.setOnClickListener(this);
        alarmCloseBt = view.findViewById(R.id.alarmClose_bt);
        alarmCloseBt.setOnClickListener(this);
        setAlarmTime = view.findViewById(R.id.setAlarmTime);
        setAlarmTime.setOnClickListener(this);
        btSendLocation = view.findViewById(R.id.bt_sendLocation);//发送定位
        btSendLocation.setOnClickListener(this);
        btSIMState = view.findViewById(R.id.bt_simState);// SIM状态
        btSIMState.setOnClickListener(this);
        lockInTimeBt = view.findViewById(R.id.lockInTime_bt); //同步时间
        lockInTimeBt.setOnClickListener(this);
        scanLightLevelSp = view.findViewById(R.id.scanLightLevel_sp);
        lightLevelSubmitBt = view.findViewById(R.id.lightLevelSubmit_bt);
        lightLevelSubmitBt.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.alarmSubmit_bt:  // 闹钟提交
                if (stringBuilderStr != null && !stringBuilderStr.equals("")){
                    System.out.println("提交闹钟内容"+stringBuilderStr);
                    socketLink.sendString(stringBuilderStr);
                }else {
                    popWindowFail("请选择时间").show();
                }
                break;
            case R.id.alarmClose_bt:  // 关闭闹钟
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("是否关闭闹钟?");
                builder.setIcon(R.drawable.info);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        socketLink.sendString("alarm:25-00");
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Toast.makeText(MainActivity.this,"你点击了取消",Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();
                break;
            case R.id.setAlarmTime: // 设置闹钟时间
                AlarmClockData();  //获取时间数据
                OptionsPickerView pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String date =  options1+options2 + "-" + options3;
                        String dateTv = options1+options2 + "时" + options3 +"分";
                        //在此获取选择到的内容
                        alarmTimeTv.setText(dateTv);
                        stringBuilder = new StringBuilder();
                        stringBuilder.append("alarm:").append(date);
                        stringBuilderStr = stringBuilder.toString();
                        if (!stringBuilderStr.equals("")){
                            chooseTv.setVisibility(View.GONE);
                        }
                        System.out.println("获取时间***"+stringBuilder.toString());
                    }
                })
                        .setTitleText("请选择时间")
                        .setContentTextSize(20)
                        .build();
                pvOptions.setPicker( options1Items,hoursItems, minItems);
                pvOptions.show();
                break;
            case R.id.lockInTime_bt: // 同步时间
                SimpleDateFormat formatter =new SimpleDateFormat("yyyy-M-d HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());
                String lockInTime = formatter.format(curDate);
                System.out.println("获取时间戳:"+lockInTime);
                StringBuilder sberTime = new StringBuilder();
                sberTime.append("time:").append(lockInTime);
                System.out.println(sberTime+"---发送时间格式---");
                socketLink.sendString(sberTime.toString());
                break;
            case R.id.bt_simState://SIM 卡状态
                socketLink.sendString("simState");
                break;
            case R.id.bt_sendLocation: // 发送位置
                System.out.println("发送位置*****  ");
                Location location = LocationUtils.getInstance(getActivity() ).showLocation();
                if (location != null) {
                    String address = "纬度：" + location.getLatitude() + "经度：" + location.getLongitude();
                    System.out.println("获取位置了"+address);
                    //定位 转化
                    double[] LatLng= ECGeoCoordinateTransformUtil.gps84_To_Gcj02(location.getLatitude(),location.getLongitude());
                    double Lat = LatLng[0];
                    double Lng = LatLng[1];
                    String latStr = String.valueOf(Lat);
                    String lngStr = String.valueOf(Lng);
                    StringBuilder sber = new StringBuilder();
                    sber.append("location:").append(lngStr).append(",").append(latStr);
                    System.out.println(sber.toString()+"经纬度拼接 ------");
                    socketLink.sendString(sber.toString());
                }
                break;
            case R.id.lightLevelSubmit_bt:  //提交亮度等级
                lightSubmitStr = scanLightLevelSp.getSelectedItem().toString().trim();
                if (lightSubmitStr.equals("设置扫码枪亮度")){
                    popWindowFail("请设置亮度等级").show();
                }else {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("light:").append(lightSubmitStr);
                    System.out.println("发送亮度-----"+stringBuilder.toString());
                    socketLink.sendString(stringBuilder.toString());
                }
                break;
            default:
                break;
        }
    }
    //接收wifi回传指令
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String str){
        System.out.println("--------高级配置---"+str+"------------");
        if (str.substring(0,10).equals("74696D653A")){
            String stringResult = asciiToString(str.substring(10));
            System.out.println(stringResult+"ASCII转String");
            popWindowSuccess("时间同步完成"+stringResult).show();
        }
        if (str.length() <=14 ){
            if (str.substring(2,4).equals("21")){
                popWindowSuccess("位置发送成功").show();
            }
            if (str.substring(0,13).equals("6C696768743A3")){// 亮度设置
                int i = Integer.parseInt(str.substring(13));
                System.out.println(i+"亮度设定----------------");
                if (i == Integer.parseInt(lightSubmitStr)){
                    popWindowSuccess("亮度设置成功--"+"当前亮度："+i).show();
                }
            }
        }else if (str.length() < 17) {
            if (str.substring(0,16).equals("616C61726D3A6F6B")){  //闹钟 设置
                popWindowSuccess("闹钟设置成功").show();
            }
            if (str.substring(0,13).equals("6C696768743A3")){   //亮度设置
                String s = asciiToString(str.substring(12));
                if (Integer.parseInt(s) == Integer.parseInt(lightSubmitStr)){
                    popWindowSuccess("亮度设置成功--"+"当前亮度："+s).show();
                }
            }
        }else {
            if (str.substring(0,18).equals("73696D53746174653A")){
                String simResult = asciiToString(str.substring(20,str.length()-2));
                System.out.println(simResult+"----sim状态----");
                simStateTv.setText(simResult);
            }
        }
    }
    //成功提示弹窗
    public Toast popWindowSuccess(final String content) {
        Toast toast =  Toast.makeText(getContext(), content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
    //失败提示弹窗
    public Toast popWindowFail(final String content) {
        Toast  toast =  Toast.makeText(getContext(), content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
  // 将16进制 ASCII转成字符串
    public static String asciiToString(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < str.length(); i += 2) {
            stringBuilder.append((char) Integer.parseInt(str.substring(i, i + 2), 16));
        }
        return stringBuilder.toString();
    }

    //  闹钟时间 选择器数据
    private void AlarmClockData() {
//        options1Items.clear()
//        options1Items.add("上午");
//        options1Items.add("下午");
        List<String> min = new ArrayList<>();
        List<String> hour = new ArrayList<>();
        List<List<String>> lists = new ArrayList<>();
        //创建最后一个列表数据（分）
        for (int i = 0; i < 60; i++) {
            if (i < 10) {
                min.add("0" + i + "分");
            } else {
                min.add(i + "分");
            }
        }
        //创建第二个列表数据（时）,同时将最后一个列表数据加入c,加入次数为第二个列表的大小
        for (int i = 0; i <= 23; i++) {
            if (i < 10) {
                hour.add("0" + i + "时");
            } else {
                hour.add(i + "时");
            }
            lists.add(min);
        }

        //将第二个列表数据加入options2Itmes,加入次数为options1Items的大小
//        for (int j = 0; j < options1Items.size(); j++) {
            hoursItems.add(hour);
//        }
        //将第三个列表数据加入options3Items,加入次数为第二个列表数据的长度
        for (int i = 0; i < hour.size(); i++) {
            minItems.add(lists);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
}
